<?php

include('../../include/functions.inc.php');
if (!isEmpty(getParam('operation'))) {
    switch (getParam('operation')) {
        case 'cargos':
            listCargos();
            break;
        case 'save':
            stepA($db, $user);
            break;
        case 'pay':
            stepB($db, $user);
            break;
        case 'new':
            preLoad($db, $user);
            break;
        case 'p':
            printInvoice($db);
            break;
    }
}

function printInvoice($db) {
    $invoice = unserialize($_SESSION["invoice"]);
    $numero = $invoice["head"]["NUMERO"];
    $serie = $invoice["serie"];
    header("Location: format.php?SERIE=$serie&NUMERO=$numero");
}

function listCargos() {
    header('Location: ../items/list.php');
}

function getNoFact($db, $entity) {
    $f = $db->query_select("cllg_factura_serie", "STATUS=1 AND FK_ENTITY=" . $entity);
    if (count($f) > 0) {
        return $f[0];
    }
    return null;
}

function getNextFactura($db, $serie, $entity) {
    $f = $db->queryToArray("select max(NUMERO) No FROM cllg_factura WHERE FK_ENTITY=" . $entity .
            " AND SERIE=" . sqlValue($serie, "text"));

    if (count($f) > 0 && !isEmpty($f[0]["No"])) {
        return $f[0]["No"];
    } else {
        return 0;
    }
}

function getNextIDFactura($db) {
    $f = $db->queryToArray("select max(ID) as No FROM cllg_factura");
    if (count($f) > 0 && !isEmpty($f[0]["No"])) {
        return $f[0]["No"];
    } else {
        return 1;
    }
}

function stepA($db, $user) {
    $next = getNextFactura($db, getParam("SERIE"), $user->entity);
    $next++;
    $serie = getParam("SERIE");
    $factura = array(
        "NUMERO" => $next,
        "SERIE" => sqlValue($serie, "text"),
        "FECHA" => sqlValue(getParam("FECHAFAC"), "date"),
        "TOTAL" => sqlValue(getParam("TOTAL"), "double"),
        "NOMBRE" => sqlValue(getParam("NOMBRE"), "text"),
        "DIRECCION" => sqlValue(getParam("DIR"), "text"),
        "NIT" => sqlValue(getParam("NIT"), "text"),
        "IVA" => sqlValue(getParam("IVA"), "double"),
        "TIPO_PAGO" => sqlValue(getParam("TPAGO"), "text"),
        "SUBTOTAL" => (getParam("TOTAL") - getParam("IVA")),
        "NO_BOLETA" => sqlValue(getParam("BOLETA"), "text"),
        "FK_ENTITY" => $user->entity,
        "STATUS" => sqlValue(getParam("STATUS"), "int"));
    //$db->query_insert("cllg_factura",$factura);


    $cargos = json_decode(stripslashes(getParam('json')), TRUE);
    $detalle = array();
    foreach ($cargos as $c) {
        $det = array("DESCRIPCION" => sqlValue($c["DESCRIPCION"], "text"),
            "CANTIDAD" => $c["CANTIDAD"],
            "SUBTOTAL" => $c["SUBTOTAL"],
            "FK_FACTURA" => 0);
        $detalle[] = $det;
        //$db->query_insert("cllg_factura_detalle",$det);
    }
    $invoice = array("head" => $factura, "detail" => $detalle);
    $invoice["serie"] = $serie;
    $invoice["total"] = getParam("TOTAL");
    $_SESSION["invoice"] = serialize($invoice);

    if ($factura["STATUS"] == 2) {
        saveAllData($db, $user);
    }
    else {
        header('Location: ../payments/wayspay.php?urlData=../invoices/data.php');
    }

}

function stepB($db, $user) {
    $invoice = unserialize($_SESSION["invoice"]);
    $head = $invoice["head"];

    $head["EFECTIVO"] = sqlValue(getParam("EFECTIVO"), "double");
    $head["TARJETA"] = sqlValue(getParam("TARJETA"), "double");
    $head["DEPOSITO"] = sqlValue(getParam("DEPOSITO"), "double");
    $head["NO_BOLETA"] = sqlValue(getParam("NO_BOLETA"), "double");
    $head["CHEQUE"] = sqlValue(getParam("CHEQUE"), "double");

    if (doubleval(getParam("CHEQUE") > 0)) {
        $invoice["chk"] = array("NUMERO" => getParam("NOCHEKE"),
            "BANCO" => getParam("BANCO"),
            "MONTO" => getParam("TOTAL"),
            "FECHACOBRO" => getParam("FECHACOBRO"),
            "CONCEPTO" => getParam("CONCEPTO"));
    }
    $invoice["head"] = $head;
    $_SESSION["invoice"] = serialize($invoice);

    saveAllData($db, $user);
}

function saveAllData($db, $user) {
    $invoice = unserialize($_SESSION["invoice"]);

    //persiste la informacion de la factura
    $head = $invoice["head"];
    $db->query_insert("cllg_factura", $head);

    $fk = getNextIDFactura($db);
    $details = $invoice["detail"];
    foreach ($details as $det) {
        $det["FK_FACTURA"] = $fk;
        $db->query_insert("cllg_factura_detalle", $det);
    }
    //guarda los datos del cheque
    $cheque = $invoice["chk"];
    if ($cheque != null) {
        $cheque["FACTURA"] = $fk;
        saveCheque($db, $cheque);
    }
    $_SESSION["invoice"] = serialize($invoice);

    if( $head["STATUS"] == 1 ) { //si la factura fue pagada!
        $res = array("R" => 1, "FACTURA" => $invoice["head"]["SERIE"] . "-" . $invoice["head"]["NUMERO"],
        "SERIE" => $invoice["head"]["SERIE"],
        "NUMERO" => $invoice["head"]["NUMERO"], "s" => getParam("STATUS"),
        "VIEW" => "data/invoices.php");
        $_SESSION['pack'] = serialize($res);
        header('Location: ../../include/transport.php');
    }
    else { //si se dejo pendiente de pago entonces se imprime la factura
        printInvoice($db);
    }
    
}

function saveCheque($db, $valCk) {
    $cheque = array("NUMERO" => sqlValue($valCk["NUMERO"], "text"),
        "FECHA" => sqlValue(date("y-m-d"), "date"),
        "MONTO" => sqlValue($valCk["MONTO"], "double"),
        "BANCO" => sqlValue($valCk["BANCO"], "text"),
        "FK_FACURA" => sqlValue($valCk["FACTURA"], "int"),
        "FECHA_COBRO" => sqlValue($valCk["FECHACOBRO"], "date"));

    $db->query_insert("cllg_cheque", $cheque);
}

function preLoad($db, $user) {
    $fac = getNoFact($db, $user->entity);
    $_SESSION["factura"] = $fac;
    header('Location: index.php');
}

?>